package com.ctsi.djcloudmqtt.util.json.jackson;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.Map;

/**
 * @author ggu
 */
public class JacksonUtil {
    /**
     * jackson 实体转json
     * @param obj
     * @return
     */
    public static String objectToString(Object obj) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * jackson 实体转Map
     * @param obj
     * @return
     */
    public static Map<String, Object> objectToMap(Object obj) {
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> map;
        try {
            map = mapper.readValue(objectToString(obj), Map.class);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * jackson json转实体
     * @param json
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T string2Bean(String json, Class<T> clazz) {
        ObjectMapper mapper = new ObjectMapper();
        T t = null;
        try {
            t = mapper.readValue(json, clazz);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return t;
    }

    /**
     * jackson map转实体
     *
     * @param map
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T map2Bean(Map<?, ?> map, Class<T> clazz) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        T t = null;
        if (!CollectionUtils.isEmpty(map)) {
            t = mapper.convertValue(map, clazz);
        }
        return t;
    }

}
